<template>
  <el-button style="width:118px;" type="primary" :loading="isLoading" @click="handleClick">
    {{ countdown > 0 ? (countdown + 's') : t('forget.textGetSmsCode') }}
  </el-button>
</template>

<script setup lang="ts">
import { ref, onBeforeUnmount } from 'vue';
import { ElButton } from 'element-plus';
import { useI18n } from 'vue-i18n'
import request from '@/config/axios'
const message = useMessage() // 消息弹窗

const { t } = useI18n()

const props = defineProps({
  countdownSeconds: {
    type: Number,
    default: 60
  },
  serviceUrl: {
    type: String,
    default: ''
  },
  mobile: {
    type: String,
    default: ''
  },
  scene: {
    type: Number,
    default: 0
  }
});


const emit = defineEmits(['success']);

const isLoading = ref(false);
const countdown = ref(0);
const countdownTimer = ref();

const handleClick = async () => {
  isLoading.value = true;
  if(props.mobile&&props.scene&&props.serviceUrl){
    try {
      const resut= await request.post({
          url: props.serviceUrl,
          data: {
            "mobile": props.mobile,
            "scene": props.scene
          }
        })

      console.log(resut)

      countdown.value = props.countdownSeconds;
      startCountdown();
      // toast
      message.success(t('login.SmsSendMsg'))
      emit('success');

    }catch (e) {

    }
  }else{
    // message.alert('error')
  }
  isLoading.value = false;

};

const startCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }

  countdownTimer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      isLoading.value = false;
      clearInterval(countdownTimer.value);
      // countdownTimer.value = null;
    }
  }, 1000);
};

onBeforeUnmount(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});
</script>

<style scoped></style>